<template>
    <view class="app-container order">
        <z-paging ref="paging" v-model="list" @query="queryList">
            <template #top>
                <up-navbar title="订单" :placeholder="true">
                    <template #left></template>
                </up-navbar>
                <view class="order-tabs">
                    <up-tabs 
                        lineColor="#f56c6c"
                        :list="tabs" 
                        :itemStyle="{ height: '40px' }"
                        :inactiveStyle="{ fontSize: '14px' }"
                        :activeStyle="{ fontSize: '14px', color: '#f56c6c' }"
                        @change="changeTabs"
                    />
                </view>
            </template>
            <view class="order-list">
                <view class="order-item" v-for="(item, index) in list" :key="index">
                    <template v-if="tabs[tabsIndex].type === 'AFTER'">
                        <view class="line flexrow">
                            <text class="tit">{{ item.consignee }} {{ item.contact }}</text>
                            <text class="tag wait">待审核</text>
                        </view>
                        <view class="line">
                            <text class="txt">订单类型：{{ item.type === 'LEASE' ? '租' : '售' }}</text>
                        </view>
                        <view class="line">
                            <text class="txt">商品名称：{{ item.goodsName }}</text>
                        </view>
                        <view class="line">
                            <text class="txt">商品数量：{{ item.quantity }}</text>
                        </view>
                        <view class="line">
                            <text class="txt">{{ item.created }}</text>
                        </view>
                        <view class="bottom flexrow">
                            <up-button text="立即审核" size="mini" type="error" :customStyle="{ margin: 0, width: '144rpx', height: '56rpx' }" @click="toApprove(item)"></up-button>
                        </view>
                    </template>
                    <template v-else>
                        <view class="line flexrow" v-if="tabs[tabsIndex].type === 'BUY' || tabs[tabsIndex].type === 'LEASE' || tabs[tabsIndex].type === 'HISTORY'">
                            <text class="tit">{{ item.clientCompanyName }}</text>
                            <text class="tag" :class="[item.payStatus]">{{ payStatus[item.payStatus] }}</text>
                            <text class="tag" :class="[item.logisticsStatus]">{{ status[item.logisticsStatus] }}</text>
                        </view>
                        <view class="line flexrow" v-else>
                            <text class="tit">{{ item.userNickName }}</text>
                            <text class="tag" :class="[item.status]">{{ orderStatus[item.status] }}</text>
                        </view>
                        <view class="line">
                            <text class="txt">商品名称：{{ item.goodsName }}</text>
                        </view>
                        <view class="line">
                            <text class="txt">订单类型：{{ item.orderType === 'LEASE' ? '租' : '售' }}</text>
                        </view>
                        <view class="line" v-if="tabs[tabsIndex].type === 'BUY' || tabs[tabsIndex].type === 'LEASE' || tabs[tabsIndex].type === 'HISTORY'">
                            <text class="txt">商品数量：{{ item.quantity || 0 }}</text>
							<text class="txt">已签收：{{ item.deliveredQuantity || 0 }}</text>
                        </view>
						<view class="line" v-if="tabs[tabsIndex].type === 'BUY' || tabs[tabsIndex].type === 'LEASE' || tabs[tabsIndex].type === 'HISTORY'">
							<text class="txt" v-if="item.orderType === 'LEASE'">租金：￥{{ convertFenToYuan(item.totalPrice) }}</text>
							<text class="txt" v-else>售价：￥{{ convertFenToYuan(item.totalPrice) }}</text>
							<text class="txt" v-if="item.orderType === 'LEASE'">押金：￥{{ convertFenToYuan(item.deposit) }}</text>
						</view>
                        <template v-else-if="tabs[tabsIndex].type === 'EXCHANGE'">
                            <view class="line">
                                <text class="txt">换货数量：{{ item.quantity }}</text>
                            </view>
                            <view class="line">
                                <text class="txt">换货理由：{{ item.clientRemark }}</text>
                            </view>
                        </template>
                        <template v-else-if="tabs[tabsIndex].type === 'RETURN'">
							<view class="line">
								<text class="txt">商品数量：{{ item.orderQuantity}} &nbsp;&nbsp;&nbsp;&nbsp; 还货数量：{{ item.quantity }}</text>
								<text class="txt">应退租金：{{ convertFenToYuan(item.priceReturn || 0) }}元 &nbsp;&nbsp;&nbsp;&nbsp; 应退押金：{{ convertFenToYuan(item.depositReturn || 0)  }}元</text>
								<text class="txt">合计应退：{{ convertFenToYuan(item.totalReturn || 0) }}元</text>
							</view>
                        </template>
                        <view class="line" v-if="tabs[tabsIndex].type === 'RETURN'">
                            <text class="txt">原订单租赁日期-起始： {{ item.leaseStartTime }}</text>
							<text class="txt">原订单租赁日期-截止： {{ item.leaseEndTime }}</text>
                        </view>
						<view class="line" v-if="tabs[tabsIndex].type === 'EXCHANGE' || tabs[tabsIndex].type === 'RETURN'">
							<text class="txt">备注：{{ item.clientRemark }}</text>
						</view>
                        <view class="order-deliver" v-if="item.status === 'CLIENT_DELIVERED' && item.merchantToReceiveQuantity > 0">
                            <template v-for="(child, key) in item.delivery" :key="key">
                                <view class="block">
                                    <view class="l flexrow">
                                        <text class="t">类型：{{ logiStatus[child.logisticsType] }}</text>
                                        <text class="t">数量：{{ child.quantity }}</text>
                                    </view>
                                    <view class="l flexrow">
                                        <text class="t f">{{ child.created }}</text>
                                        <up-button text="已签收" size="mini" color="#999" :customStyle="{ margin: 0, width: '96rpx', height: '40rpx' }" v-if="child.status === 'DELIVERED'"></up-button>
                                        <template v-else>
                                            <up-button :loading="currIndex === index && currKey === key && loading" text="确认收货" size="mini" type="error" :customStyle="{ margin: 0, width: '96rpx', height: '40rpx' }" @click="toReceiptDelivery(child, index, key)"></up-button>
                                        </template>
                                    </view>
                                </view>
                            </template>
                        </view>
                        <view class="bottom flexrow">
                            <!-- 标记已支付 -->
                            <up-button text="确认收款" size="mini" type="error" :loading="paidloading && paidindex === index" :customStyle="{ margin: '0 0 0 20rpx', width: '144rpx', height: '56rpx' }" @click="toPaid(item, index)" v-if="item.payStatus === 'UN_PAID'"></up-button>
                            <!-- exchange -->
                            <up-button text="立即审核" size="mini" type="primary" :customStyle="{ margin: '0 0 0 20rpx', width: '144rpx', height: '56rpx' }" @click="toExchangeApprove(item)" v-if="item.status === 'APPROVING' && tabs[tabsIndex].type === 'EXCHANGE'"></up-button>
                            <!-- return -->
                            <up-button text="立即审核" size="mini" type="primary" :customStyle="{ margin: '0 0 0 20rpx', width: '144rpx', height: '56rpx' }" @click="toReturnApprove(item)" v-if="item.status === 'APPROVING' && tabs[tabsIndex].type === 'RETURN'"></up-button>
                            <!-- buy lease -->
                            <up-button text="立即发货" size="mini" type="success" :customStyle="{ margin: '0 0 0 20rpx', width: '144rpx', height: '56rpx' }" @tap="toOrderInfo(item)" v-if="item.merchantToDeliverQuantity > 0 && item.logisticsStatus === 'WAITING_MERCHANT_DELIVERY'"></up-button>
                            <!-- exchange -->
                            <up-button text="立即发货" size="mini" type="success" :customStyle="{ margin: '0 0 0 20rpx', width: '144rpx', height: '56rpx' }" @tap="exchangeTodeliver(item)" v-if="item.merchantToDeliverQuantity > 0 && item.status === 'MERCHANT_CONFIRMED'"></up-button>
                        </view>
                    </template>
                </view>
            </view>
            <template #bottom>
                <view class="order-zw">
                    <up-gap height="50"></up-gap>
                </view>
            </template>
        </z-paging>
        <zzk-order-approve :show="show" :id="curr.id" @close="show = false" @update="updateList"></zzk-order-approve>
        <zzk-exchange-approve :show="exchangeShow" :id="curr.id" @close="exchangeShow = false" @update="updateList"></zzk-exchange-approve>
        <zzk-return-approve :show="returnShow" :id="curr.id" @close="returnShow = false" @update="updateList"></zzk-return-approve>
        <zzk-tabbar></zzk-tabbar>
    </view>
</template>

<script setup>
import { ref } from 'vue'
import { onLoad, onUnload } from '@dcloudio/uni-app'
import { orderList, orderExchange, orderReturn, preOrders, merchantConfirm, updatePaidUnderLine } from '@/api/order.js'
import { orderStatus, payStatus } from '@/utils/status'
import { linkto, showToast, convertFenToYuan } from '@/utils/util'

const tabs = ref([
    { name: '后付订单', type: 'AFTER', unit: '后付' },
    { name: '销售订单', type: 'BUY', unit: '售' },
    { name: '出租订单', type: 'LEASE', unit: '租' },
    { name: '换货', type: 'EXCHANGE', unit: '换' },
    { name: '还货', type: 'RETURN', unit: '还' },
    { name: '历史订单', type: 'HISTORY', unit: '' },
])
const tabsIndex = ref(0)
const paging = ref(null)
const list = ref([])

// 审核
const show = ref(false)
const curr = ref({})
const exchangeShow = ref(false)
const returnShow = ref(false)

const status = ref({
    'WAITING_MERCHANT_DELIVERY': '待发货',
    'WAITING_CLIENT_CONFIRM': '待客户收货',
    'CLIENT_CONFIRMED': '客户已收货'
})

const logiStatus = ref({
    'LOGISTICS': '物流快递',
    'MERCHANT_SEND': '商家配送上门',
    'CLIENT_SELF_PICKUP': '客户到附近营业网点自提',
})

// 换货 - 确认收货
// loading
const currIndex = ref(0)
const currKey = ref(0)
const loading = ref(false)

onLoad(() => {
    uni.hideTabBar()
    
    uni.$on('refresh_order', () => {
        paging.value.reload()
    })
})

onUnload(() => {
    uni.$off('refresh_order')
})

const queryList = (pageNo, pageSize) => {
    const obj = tabs.value[tabsIndex.value]
    const params = {
        page: pageNo,
        size: pageSize,
    }
    if (obj.type === 'BUY' || obj.type === 'LEASE') {
        params.type = obj.type
        params.onlyCompleted = false
        orderList(params).then(res => {
            paging.value.complete(res.records)
        })
    } else if (obj.type === 'EXCHANGE') {
        orderExchange(params).then(res => {
            paging.value.complete(res.records)
        })
    } else if (obj.type === 'RETURN') {
        orderReturn(params).then(res => {
            paging.value.complete(res.records)
        })
    } else if (obj.type === 'AFTER') {
        params.status = 'PENDING_EFFECTIVE'
        preOrders(params).then(res => {
            paging.value.complete(res.records)
        })
    } else if (obj.type === 'HISTORY') {
        params.onlyCompleted = true
        orderList(params).then(res => {
            paging.value.complete(res.records)
        })
    }
}

const changeTabs = (e) => {
    tabsIndex.value = e.index
    paging.value.reload()
}

const toApprove = (item) => {
    show.value = true
    curr.value = item
}

const toExchangeApprove = (item) => {
    exchangeShow.value = true
    curr.value = item
}

const toReturnApprove = (item) => {
    returnShow.value = true
    curr.value = item
}

const updateList = () => {
    show.value = false
    exchangeShow.value = false
    returnShow.value = false
    paging.value.reload()
}

// 租售发货
const toOrderInfo = (item) => {
    let type = tabs.value[tabsIndex.value].type
    linkto(`/pages/order/info?id=${item.id}&type=${type}`)
}

// 换货发货
const exchangeTodeliver = (item) => {
    let type = tabs.value[tabsIndex.value].type
    linkto(`/pages/order/exchange?id=${item.originOrderId}&num=${item.merchantToDeliverQuantity}&applyId=${item.id}`)
}

const toReceiptDelivery = (item, index, key) => {
    uni.showModal({
        title: '提示',
        content: '是否确认收货?',
        success: res => {
            if (res.confirm) {
                loading.value = true
                merchantConfirm(item.id).then(r => {
                    loading.value = false
                    paging.value.reload()
                    showToast('收货成功')
                }).catch(e => {
                    loading.value = false
                })
            }
        }
    })
}

// 标记已支付
const paidloading = ref(false)
const paidindex = ref(0)
const toPaid = (item, index) => {
    uni.showModal({
        title: '提示',
        content: '是否立即确认收款?',
        success: r => {
            if (r.confirm) {
                confirmPaid(item, index)
            }
        }
    })
}

const confirmPaid = (item, index) => {
    const data = {
        orderNos: item.orderNo,
        totalAmount: item.totalPay 
    }
    paidloading.value = true
    paidindex.value = index
    updatePaidUnderLine(data).then(res => {
        showToast('确认成功')
        paidloading.value = false
        paging.value.reload()
    }).catch(e => {
        paidloading.value = false
    })
}
</script>

<style lang="scss" scoped>
.order {
    &-tabs {
        background-color: #fff;
    }
    &-list {
        padding: 20rpx $zzk-margin 0;
    }
    &-item {
        background-color: #fff;
        padding: 32rpx;
        border-radius: 8rpx;
        margin-bottom: 20rpx;
        .tit {
            font-size: 28rpx;
            line-height: 48rpx;
            font-weight: 700;
            flex: 1;
        }
        .tag {
            font-size: 24rpx;
            line-height: 48rpx;
            padding: 0 8rpx;
            background-color: $u-info-light;
            color: $u-info;
            border-radius: 4rpx;
            margin-left: 16rpx;
            &.wait, &.APPROVED, &.MERCHANT_CONFIRMED {
                background-color: $u-primary-light;
                color: $u-primary;
            }
            &.WAITING_MERCHANT_DELIVERY, &.CLIENT_DELIVERED, &.MERCHANT_DELIVERED {
                background-color: $u-success-light;
                color: $u-success;
            }
            &.WAITING_CLIENT_CONFIRM, &.REJECTED, &.UN_PAID {
                background-color: $u-error-light;
                color: $u-error;
            }
            &.CLIENT_CONFIRMED {
                background-color: $u-info-light;
                color: $u-info;
            }
            &.APPROVING {
                background-color: $u-warning-light;
                color: $u-warning;
            }
        }
        .txt {
            font-size: 28rpx;
            line-height: 48rpx;
            color: #999;
        }
        .line {
            justify-content: space-between;
            align-items: center;
        }
        .bottom {
            justify-content: flex-end;
        }
    }
    &-deliver {
        padding-top: 8rpx;
        margin-bottom: 16rpx;
        .block {
            margin-bottom: 16rpx;
            background-color: #ecf5ff;
            padding: 16rpx 20rpx;
            border-radius: 8rpx;
            &:last-child {
                margin-bottom: 0;
            }
        }
        .t {
            font-size: 24rpx;
            line-height: 40rpx;
            padding-right: 20rpx;
            &.f {
                flex: 1;
            }
        }
    }
    &-zw {
        padding-bottom: constant(safe-area-inset-bottom);
        padding-bottom: env(safe-area-inset-bottom);
    }
}
</style>